﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Resources;
using System.Web;
using System.Xml;

namespace AVCare.LMS.Util
{
    public class LanguageHelper
    {
        private static string _currentLang = "zh-cn";

        public static string CurrentLang
        {
            get { return LanguageHelper._currentLang; }
            set { LanguageHelper._currentLang = value.ToLower(); }
        }

        private static Dictionary<string, Dictionary<string, string>> langs = new Dictionary<string, Dictionary<string, string>>();
        private static HttpContext _context = null;

        public static string GetString(string key)
        {
            Dictionary<string, string> dir = null;
            try
            {
                dir = langs[_currentLang];
                if (dir == null)
                {
                    dir = langs["zn-cn"];
                    _currentLang = "zh-cn";
                }
                if (!dir.Keys.Contains(key))
                {
                    return key;
                }
                return dir[key.ToLower()];
            }
            catch
            {
                dir = langs["zh-cn"];
                _currentLang = "zh-cn";
                return dir[key.ToLower()];
            }
        }

        public static void Init(HttpContext context)
        {
            _context = context;
            HttpServerUtility server = context.Server;

            DirectoryInfo di = new DirectoryInfo(server.MapPath("~/Content/langs"));
            FileInfo[] files = di.GetFiles("*.xml");
            foreach (var item in files)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(item.FullName);
                XmlNode root = doc.SelectSingleNode("/Language");
                Dictionary<string, string> dir = new Dictionary<string, string>();
                foreach (XmlNode node in root.ChildNodes)
                {
                    dir.Add(node.Attributes["key"].Value, node.Attributes["value"].Value);
                }
                langs.Add(root.Attributes["UICulture"].Value.ToLower(), dir);
            }
        }
    }
}
